package cn.javasea.websocket.handler.impl;

import cn.javasea.websocket.entity.JsonMessage;
import cn.javasea.websocket.entity.SimpleUser;
import cn.javasea.websocket.handler.Action;
import cn.javasea.websocket.utils.WsBroadcastUtil;
import cn.javasea.websocket.websocket.LoginUserCache;
import cn.javasea.websocket.entity.SessionUser;
import com.zhirui.oauth.sucket.handler.Handler;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: Ethan_Fung
 * @description:
 * @date: 2020/3/18 17:02
 * @version: 1.0
 **/
@Component
public class LinkOpenHandler implements Handler {


    /**
     * 调用执行对应方法
     *
     * @param message
     * @param session
     * @return
     */
    @Override
    public Object action(String message, Session session) {
        String tenantId = session.getPathParameters().get("tenantId");
        String userId = session.getPathParameters().get("userId");
        JsonMessage jm = new JsonMessage(Action.LINK_OPEN.name(),null, null, null, null);

        Set<Map.Entry<String, SessionUser>> set = LoginUserCache.getAllByMap().entrySet();
        ArrayList<SimpleUser> tUsers = new ArrayList<>();
        set.stream().filter(s -> s.getValue().getTenantId().equals(tenantId))
                .filter(s -> !s.getValue().getUserId().equals(userId))
                .forEach(us -> {
                    SimpleUser user = new SimpleUser();
                    user.setUserId(us.getValue().getUserId());
                    user.setUserName(us.getValue().getUserName());
                    tUsers.add(user);
                });
        jm.setData(tUsers);
        List<String> userIds = tUsers.stream().map(SimpleUser::getUserId).collect(Collectors.toList());
        if (null != userIds && !userIds.isEmpty()) {
            try {
                WsBroadcastUtil.broadcastNotifications(userIds, jm);
            } catch (Exception e) {
            }
        }
        return null;
    }
}
